package com.yong.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    // 成功
    public String payment_OK(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "\t paymentInfo_ok,id" + id;
    }

    // 失败
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")  //3秒钟以内就是正常的业务逻辑
    })
    public String paymentInfo_Timeout(Integer id){
        //int age = 10/0;
        int timeNumber = 3;
        try { TimeUnit.SECONDS.sleep(timeNumber); } catch (Exception e) { e.printStackTrace(); }
        return "线程池：" + Thread.currentThread().getName() + "\t paymentInfo_Timeout,id" + id+"耗时："+timeNumber;
    }

    /**
     * 一旦调用服务方法失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
     *
     * paymentInfo_Timeout方法故意制造连个异常
     * 1、int age = 10/0; 计算异常
     * 2、我们设置线程运行时间为3秒，但是程序需要执行5秒，超时异常
     *
     * 当前服务不可用了，做服务降级，兜底方法 paymentInfo_TimeOutHandler
     */
    public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池："+Thread.currentThread().getName()+"   系统繁忙, 请稍候再试  ,id：  "+id+"\t"+"哭了哇呜";
    }
}
